package com.ihome.android.market2.asynctask;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.ihome.android.EAApp;
import com.ihome.android.academy.DetailActivity;
import com.ihome.android.academy.InitialActivity;
import com.ihome.android.analytic.JsonAnalytic;
import com.ihome.android.common.ConfigUtil;
import com.ihome.android.http.HttpActions;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.academy.R;
import com.ihome.android.academy.service.GetMarketInfoService;
import com.ihome.android.academy.service.GetMarketInfoSynObj;
import com.ihome.android.market2.info.LoginResult;
import com.ihome.android.market2.info.TemplateContentInfo;
import com.ihome.android.market2.info.WelcomeInfo;
import com.ihome.android.market2.view.DialogFactory;
import com.ihome.android.market2.view.DialogFactory.onBtnClickListener;
import com.ihome.android.market2.view.MyProgressDialog;
import com.ihome.android.util.SPMgr;
import com.ihome.android.util.Util;
import com.ihome.android.util.exception.ITVException;
import com.ihome.android.util.log.LogUtil;
import com.ihome.android.util.log.UserBehaviorLog;
import com.ihome.android.util.log.UserBehaviorLog.NotifyType;
import com.ihome.android.util.log.UserBehaviorLog.UserBehavior;

/**
 * 用户登陆认证
 * 
 * @author Emerson
 * 
 */
public class UserLoginTask extends AsyncTask<Bundle, Integer, Bundle> {
	private final String		TAG	= UserLoginTask.class.getSimpleName();
	private Context				context;
	private MyProgressDialog	progressDialog;
	private WelcomeInfo			welcomInfo;

	public UserLoginTask(Context context) {
		this.context = context;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();

		if (!(context instanceof Activity))
			return;
		progressDialog = MyProgressDialog.getDialog(context, context.getString(R.string.is_login_in));
		progressDialog.show();
		progressDialog.setCancelable(true);
		progressDialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				if (UserLoginTask.this.getStatus().compareTo(AsyncTask.Status.FINISHED) != 0)
					UserLoginTask.this.cancel(true);
			}
		});
	}

	@Override
	protected Bundle doInBackground(Bundle... params) {
		Bundle b = params[0];
		String username = "" + b.getString(HttpKeys.KEY_APPUSERNAME);
		String pwd = "" + b.getString(HttpKeys.KEY_LOGINPASSWORD);
		int operateFlag = b.getInt(HttpKeys.KEY_OPERATEFLAG);
		LogUtil.v(TAG, "username = " + username);
		LogUtil.v(TAG, "pwd = " + pwd);
		if (TextUtils.isEmpty(pwd) || TextUtils.isEmpty(username)) {
			String[] msgx = {"","","","","user.login",""};
			UserBehaviorLog.getInstance().writeLog(UserBehavior.STORERUN_EXCEPTION, NotifyType.TYPE_FAILURE, "", msgx);
			return null;
		}

		try {
			String result = new HttpActions(context).loginReq(username, pwd, operateFlag);
			LogUtil.v(TAG, "result = " + result);
			if (!TextUtils.isEmpty(result)) {
				LoginResult mLoginResult = JsonAnalytic.getInstance().anslyseLoginResult(result);
				LogUtil.v(TAG, "LoginResult = " + mLoginResult.toString());
				ConfigUtil.SessionKey = mLoginResult.getSessionkey();
				ConfigUtil.accountInfo = mLoginResult.getDetail();
				ConfigUtil.dataGatherSize = mLoginResult.getDataGatherSize();
				if (ConfigUtil.accountInfo != null && !TextUtils.isEmpty(ConfigUtil.accountInfo.getPayPassword())) {
					Util.saveUserPayPwd(context, ConfigUtil.accountInfo.getPayPassword());
				}

				if (context instanceof Activity) {
					String areaCode = SPMgr.getInstance(context).getElement(HttpKeys.KEY_AREANO, "320000");
					String welcome = new HttpActions(context).getWelcomeInfo(areaCode);
					welcomInfo = JsonAnalytic.getInstance().anslyseWelcomeInfo(welcome);
					LogUtil.d(TAG, "welcome = \n" + welcomInfo.toString());
					EAApp.getApp().cacheKey = welcomInfo.getCacheKey();

					String templateTitle = new HttpActions(context).getTemplateContent(EAApp.getApp().cacheKey);
					LogUtil.d(TAG, "templateTitle = \n" + templateTitle);
					
					List<TemplateContentInfo> tempList = new ArrayList<TemplateContentInfo>();
					tempList  = JsonAnalytic.getInstance().anslyseTemplateContent(templateTitle);
//					EAApp.getApp().mCategoryList = JsonAnalytic.getInstance().anslyseTemplateContent(templateTitle);

					EAApp.getApp().mCategoryList.clear();
					/**
					 * 过滤 Type不为1的数据， 1.栏目，2.应用，4.专题；
					 */
					for (TemplateContentInfo titleInfo : tempList) {
						if (titleInfo.getType() == 1) {
							EAApp.getApp().mCategoryList.add(titleInfo);
						}
					}
					LogUtil.d(TAG, "mCategoryList size = " + EAApp.getApp().mCategoryList.size());
				}
			}
			else {
				cancel(true);
			}

		} catch (ITVException e) {
			e.printStackTrace();
			LogUtil.e(TAG, e.toString());
			b.putInt(HttpKeys.KEY_CODE, e.getStatusCode());
			b.putString(HttpKeys.KEY_DESCRIPTION, e.getMessage());
		}
		return b;
	}

	@Override
	protected void onPostExecute(Bundle result) {
		super.onPostExecute(result);
		if (progressDialog != null)
			progressDialog.dismiss();
		if (result == null)
			return;

		/** 请求出错处理 */
		if (result.containsKey(HttpKeys.KEY_CODE) && context instanceof Activity) {

			String[] msgx = {"","","","","user.login",""};
			UserBehaviorLog.getInstance().writeLog(UserBehavior.STORERUN_EXCEPTION, NotifyType.TYPE_FAILURE, "", msgx);
			if(ITVException.HTTP_GET_HTTP_URL_CONN_IO_EXCEPTION == result.getInt(HttpKeys.KEY_CODE)){

				DialogFactory.onBtnClickListener don = new onBtnClickListener() {

					public void btnRightClickListener(View v) {
						EAApp.getApp().exitApp(true);
					}

					public void btnNeutralClickListener(View v) {


					}

					public void btnLeftClickListener(View v) {
						// TODO Auto-generated method stub
						Bundle loginInfo = new Bundle();
						loginInfo.putString(HttpKeys.KEY_APPUSERNAME, Util.getOTTUserName(context.getApplicationContext()));
						loginInfo.putString(HttpKeys.KEY_LOGINPASSWORD, Util.getUserPwd(context.getApplicationContext()));
						loginInfo.putInt(HttpKeys.KEY_OPERATEFLAG, 1);
						new UserLoginTask(context).execute(loginInfo);
					}

					@Override
					public void btnCloseClickListener(View v) {

					}
				};

				new DialogFactory(context).showDialog2Btn(context.getString(R.string.attention_error), result.getString(HttpKeys.KEY_DESCRIPTION) + "(" + result.getInt(HttpKeys.KEY_CODE) + ")","重试","取消",don);
			}else{
				if(ITVException.CODE_LOGINOUT_THREE == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_LOGINOUT_ONE == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_SESSIONKEY == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_LOGIN_ONE == result.getInt(HttpKeys.KEY_CODE) ||ITVException.CONTENT_NO_MATCH == result.getInt(HttpKeys.KEY_CODE) || -88505==result.getInt(HttpKeys.KEY_CODE)){
					new DialogFactory(context).showDialog("",result.getString(HttpKeys.KEY_DESCRIPTION) + "(" + result.getInt(HttpKeys.KEY_CODE) + ")",context.getString(R.string.dialog_ok),new onBtnClickListener() {
						
						@Override
						public void btnRightClickListener(View v) {
							// TODO Auto-generated method stub
						}
						
						@Override
						public void btnNeutralClickListener(View v) {
							// TODO Auto-generated method stub
							
						}
						
						@Override
						public void btnLeftClickListener(View v) {
							// TODO Auto-generated method stub
							EAApp.getApp().exitApp(true);
						}
						
						@Override
						public void btnCloseClickListener(View v) {
							// TODO Auto-generated method stub
							
						}
					});
					return;
				}
				new DialogFactory(context).showDialog(result.getString(HttpKeys.KEY_DESCRIPTION) + "(" + result.getInt(HttpKeys.KEY_CODE) + ")");
			}


			return;
		}

		if (context instanceof GetMarketInfoService) {
			LogUtil.v(TAG, "------ GetMarketInfoService --> Success");
			new Thread() {
				public void run() {
					synchronized (GetMarketInfoSynObj.getInstance()) {
						// 处理完成，唤醒等待的同步对象
						GetMarketInfoSynObj.getInstance().notifyAll();
					}
				};
			}.start();
		}
		/** 登陆成功后页面跳转到主页面 */
		else if (context instanceof InitialActivity && welcomInfo != null) {
//			Intent intent = new Intent(context, MainActivity.class);
//			context.startActivity(intent);
//			((Activity) context).finish();
//			((InitialActivity)context).startInitAD(welcomInfo);
		}
		else if (context instanceof DetailActivity) {
			LogUtil.v(TAG, "------ UserLoginTask -->  doSearch()");
			((DetailActivity) context).doSearch();
		}

		/** 用户行为统计 登录应用商店 */
		String[] msg = { "", "", "", "", "user.login", "" };
		UserBehaviorLog.getInstance().writeLog(UserBehavior.LOGIN, NotifyType.TYPE_NORMAL, "", msg);

	}

	@Override
	protected void onCancelled() {
		super.onCancelled();
		LogUtil.i(TAG, "--> onCancelled");
		if (progressDialog != null)
			progressDialog.dismiss();
		if (context instanceof InitialActivity) {
			((InitialActivity)context).exitApp();
		}
	}

}
